package hz;

import java.net.*;
import java.io.*;

public class GameThread extends Thread {

	private Socket socket;
	private PrintWriter out;
	private BufferedReader in;
	int id;

	public GameThread(Socket socket) {
		super("My Game Thread");
		this.socket = socket;

		try {
			out = new PrintWriter(socket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void addToGlabalList(int id) {
		this.id = id;
		GameServer.add(id, this);
	}

	boolean tellAMyId(int aid) {
		return GameServer.sayTo(aid, String.format("{\"bid\":%d}", id));
	}

	boolean tellWhoWhereIMove(int who, int row, int col, String msg) {
		if (msg == null)
			msg = "ok";
		return GameServer.sayTo(who, String.format(
				"{\"row\":%d,\"col\":%d,\"status\":\"%s\"}", row, col, msg));
	}

	public void say(String word) {
		System.out.println("server says to " + id + ": " + word);
		out.println(word);
	}

	@Override
	public void run() {
		try {
			String inputLine, outputLine;
			GameProtocol protocol = new GameProtocol(this);

			while ((inputLine = in.readLine()) != null) {
				System.out.println("id" + id + ": " + inputLine);
				outputLine = protocol.processInput(inputLine);
				System.out.println("server says to " + id + ": " + outputLine);
				out.println(outputLine);
				if (outputLine.equals("bye"))
					break;
			}
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
